var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express'});
});
var http = require("http");

var faker = require('faker');
var fs = require('fs');


function getOptions(path) {
    return {
        "method": "POST",
        "hostname": "localhost",
        "port": "7474",
        "path": "/db/data/" + path,
        "headers": {
            "accept": "application/json; charset=UTF-8",
            "authorization": "bmVvNGo6MTIzNDU2",
            "content-type": "application/json",
            "cache-control": "no-cache"
        }
    }
}

//创建节点关系
function createRelationship() {
    fs.readdir("./guanxi/", function (err, files) {
        files.forEach(function (file, index) {
            var data = fs.readFileSync("./guanxi/" + file);
            var path = fs.readFileSync('./nodePath');
            var arrPath = JSON.parse("[" + path.toString().substring(0, path.toString().length - 1) + "]");
            var a, b;
            arrPath.forEach(function (item) {
                if (item[JSON.parse(data.toString()).outward]) {
                    a = item[JSON.parse(data.toString()).outward];
                }
                if (item[JSON.parse(data.toString()).inward]) {
                    b = item[JSON.parse(data.toString()).inward]
                }
            });
            var outId = a.substr(a.indexOf("node/") + 5, a.length);
            var req = http.request(getOptions("node/" + outId + "/relationships"), function (res) {
                var chunks = [];

                res.on("data", function (chunk) {
                    chunks.push(chunk);
                });

                res.on("end", function () {
                    var body = Buffer.concat(chunks);
                    console.log(body.toString());
                });
            });
            req.write(JSON.stringify({to: b, type: 'LOVES'}));
            req.end();
        })
    });
}

//自动创建5种类型的节点
function createNode() {
    for (var i = 1; i < 6; i++) {
        fs.readdir("./" + i + "/", function (err, files) {
            if (err) {
                return console.error(err);
            }
            var arr = [];
            var typeArr = ["a", "b", "c", "d", "e"];
            files.forEach(function (file, index) {
                var data = fs.readFileSync("./" + i + "/" + file);
                var api = {
                    "method": "POST",
                    "to": "/cypher",
                    "body": {
                        "query": "CREATE (n:" + typeArr[i - 1] + " { props }) RETURN n",
                        "params": {"props": JSON.parse(data.toString())}
                    }
                };
                arr.push(api);
            });
            var req = http.request(getOptions("batch"), function (res) {
                var chunks = [];

                res.on("data", function (chunk) {
                    chunks.push(chunk);
                });

                res.on("end", function () {
                    var body = Buffer.concat(chunks);
                    var arrPath = fs.readFileSync('./nodePath').toString();
                    JSON.parse(body.toString()).forEach(function (item) {
                        var data = {};
                        data[item.body.data[0][0].data.id] = item.body.data[0][0].self;
                        arrPath += JSON.stringify(data) + ","
                    });
                    fs.writeFile('./nodePath', arrPath, function (err) {
                        console.log("数据写入成功！");
                    })
                });
            });
            req.write(JSON.stringify(arr));
            req.end();
        });
    }
}

//生成关系文档
function createRelationshipFile() {
    var arr = [[1, 2], [3, 4], [5, 1]];
    arr.forEach(function (item) {
        fs.readdir("./" + item[0] + "/", function (err, files) {
            if (err) {
                return console.error(err);
            }
            fs.readdir("./" + item[1] + "/", function (err, files2) {
                files.forEach(function (file, index) {
                    var data = {};
                    data.outward = file;
                    data.inward = files2[index];
                    fs.open('./guanxi/' + faker.random.uuid(), 'w+', function (err, fd) {
                        if (err) {
                            return console.error(err);
                        }
                        fs.write(fd, JSON.stringify(data), function (e) {
                            if (e) throw e;
                            fs.closeSync(fd);
                        });
                        console.log("文件打开成功！");
                    });
                });
            });
        });
    });
}


//获取随机的数据
function getData() {
    var data = {};
    data.name = faker.name.findName();
    data.address = faker.address.streetName();
    data.email = faker.internet.email();
    data.phone = faker.phone.phoneNumberFormat();
    data.commerce = faker.commerce.productAdjective();
    data.company = faker.company.catchPhraseDescriptor();
    data.finance = faker.finance.currencyName();
    data.hacker = faker.hacker.adjective();
    data.lorem = faker.lorem.paragraphs(500);
    data.id = faker.random.uuid();
    return data;
}

//每个类型创建50个文档
function createFile() {
    for (var j = 0; j < 50; j++) {//50是创建文档的数量
        for (var i = 1; i < 6; i++) {
            fs.open('./' + i + '/' + data.id, 'w+', function (err, fd) {
                if (err) {
                    return console.error(err);
                }
                fs.write(fd, JSON.stringify(getData()), function (e) {
                    if (e) throw e;
                    fs.closeSync(fd);
                });
                console.log("文件打开成功！");
            });
        }
    }
}


function getCreateOptions(type, id) {
    return {
        "method": "POST",
        "hostname": "localhost",
        "port": "9200",
        "path": "/test/" + type + "/" + id + "/_create",
        "headers": {
            "content-type": "application/json",
            "cache-control": "no-cache"
        }
    }
}

//elasticsearch上传文档数据
//上传5种类型的文档
// for (var i = 1; i < 6; i++) {
//     postFile(i);
// }
//上传关系文档
// postFile("guanxi");
function postFile(i) {
    fs.readdir("./" + i + "/", function (err, files) {
        if (err) {
            return console.error(err);
        }

        files.forEach(function (item) {

            var data = fs.readFileSync("./" + i + "/" + item);
            var req = http.request(getESOptions(i, item), function (res) {
                var chunks = [];

                res.on("data", function (chunk) {
                    chunks.push(chunk);
                });

                res.on("end", function () {
                    var body = Buffer.concat(chunks);
                    console.log(body.toString());
                });
            });
            req.write(data.toString());
            req.end();
        })
    });
}


function getQueryOptions(type, query) {
    return {
        "method": "GET",
        "hostname": "localhost",
        "port": "9200",
        "path": "/test/" + type + "/_search?q=" + query,
        "headers": {
            "content-type": "application/json",
            "cache-control": "no-cache"
        }
    }
}

//通过传入type id或者type 单词搜索文档  例如 queryTypeFile(1,"0f024d7e-db68-4cc2-aaed-d038bcb8d3a1")
function queryTypeFile(type, query) {

    var req = http.request(getQueryOptions(type, query), function (res) {
        var chunks = [];


        res.on("data", function (chunk) {
            chunks.push(chunk);
        });

        res.on("end", function () {
            var body = Buffer.concat(chunks);
            console.log(body.toString());
        });
    });

    req.write(JSON.stringify({}));
    req.end();
}

//通过id查询关系文档
function queryRelationshipId(id) {
    var req = http.request(getQueryOptions("guanxi", id), function (res) {
        var chunks = [];

        res.on("data", function (chunk) {
            chunks.push(chunk);
        });

        res.on("end", function () {
            var body = Buffer.concat(chunks);
            getRelatedFile(id);
            JSON.parse(body.toString()).hits.hits.forEach(function (item) {
                var id = id == item._source.outward ? item._source.inward : item._source.outward;
                getRelatedFile(id);
            })
        });
    });
    req.end();
}

var arr = [];
//传入id，获取文档
function getRelatedFile(id) {
    var req = http.request(getQueryOptions("", id), function (res) {
        var chunks = [];

        res.on("data", function (chunk) {
            chunks.push(chunk);
        });

        res.on("end", function () {
            var body = Buffer.concat(chunks);
            arr.push(body.toString());
            console.log(arr.length)
        });
    });
    req.end();
}

//传入一个单词，查询所有文档，然后调用queryRelationshipId函数
function queryIdGetRelatedFile(data) {
    var req = http.request(getQueryOptions("", data), function (res) {
        var chunks = [];

        res.on("data", function (chunk) {
            chunks.push(chunk);
        });

        res.on("end", function () {
            var body = Buffer.concat(chunks);
            JSON.parse(body.toString()).hits.hits.forEach(function (item) {
                queryRelationshipId(item._source.id);
            })
        });
    });

    req.write(JSON.stringify({}));
    req.end();
}

module.exports = router;
